import { Options } from '@/hooks/useHttpHook';
import { Toast } from 'antd-mobile';

export type Res = {
  status?: number | string;
  data?: [] | {};
  errorMsg?: string | undefined | null;
};

export default function Http({
  url,
  method = 'POST',
  headers,
  body = {},
  setLoadning,
  setResult,
}: Options) {
  setLoadning?.(true);
  const defaultHeaders = {
    'content-type': 'application/json',
  };
  let params: object | undefined = undefined;
  if (method.toUpperCase() === 'POST') {
    params = {
      method,
      body: JSON.stringify(body),
      headers: {
        ...defaultHeaders,
        ...headers,
      },
    };
  }
  return new Promise(async (resolve, reject) => {
    try {
      const res: Res = await fetch('/api' + url, params).then((res) =>
        res.json(),
      );
      if (res.status === 200) {
        resolve(res.data);
        setResult?.(res.data);
      } else {
        Toast.fail(res.errorMsg);
        reject(res.errorMsg);
      }
    } catch (error) {
      Toast.fail(error);
      reject(error);
    } finally {
      setLoadning?.(true);
    }
  });
}
